package com.xiaoming.backend.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.xiaoming.backend.result.exception.error.AppError;
import com.xiaoming.backend.result.exception.AppErrorException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonUtil {
    private static ObjectMapper mapper;

    public static String objToJson(Object obj){
        try {
            if (mapper == null){
                objectMapper();
            }
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error(String.valueOf(AppError.DATA_ERROR));
            log.error(e.toString());
            throw new AppErrorException(AppError.DATA_ERROR);
        }
    }

    public static <T> T jsonToObj(String json,Class<T> objClass){
        try {
            if (mapper == null){
                objectMapper();
            }
            return mapper.readValue(json, objClass);
        } catch (JsonProcessingException e) {
            log.error(String.valueOf(AppError.DATA_ERROR));
            log.error(e.toString());
            throw new AppErrorException(AppError.DATA_ERROR);
        }
    }

    public static void objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 注册 JavaTimeModule
        objectMapper.registerModule(new JavaTimeModule());
        // 禁用时间戳格式（使用 ISO-8601 格式）
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper =  objectMapper;
    }
}
